import 'package:flutter/material.dart';
import 'package:cbec_app/components/base/base_image.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get_rx/src/rx_typedefs/rx_typedefs.dart';
import '../../../components/common/common_style.dart';
import '../../../utils/Tools.dart';
import '../../goods/view/custom_countdown_timer.dart';

class PresaleOrderItem extends StatefulWidget {
  final Map itemInfo;

  final Function(OperateActionType, Map)? onCallback; // 回调参数，接受两个参数

  final Function? detailOnTap;

  const PresaleOrderItem({super.key, required this.itemInfo, this.onCallback, this.detailOnTap});

  @override
  State<PresaleOrderItem> createState() => _PresaleOrderItemState();
}

class _PresaleOrderItemState extends State<PresaleOrderItem> {
  late String sn;
  late List goodsList;
  late Widget statusWidget;
  late Widget priceWidget;
  late Widget operateWidget;
  //预售订单类型 1-全款预售 2-定金预售
  late int presaleType;
  //是否已付尾款 0-否 1-是
  late int finalStatus;

  @override
  void initState() {
    super.initState();
    sn = widget.itemInfo['sn'];
    presaleType = widget.itemInfo['presaleType'];
    goodsList = widget.itemInfo['goodsInfo'];
    finalStatus = widget.itemInfo['finalStatus'];
    statusWidget = createStatusWidget();
    priceWidget = createPriceWidget();
    operateWidget = createOperateWidget();
  }

  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: () {
        if (widget.detailOnTap != null) {
          widget.detailOnTap!();
        }
      },
      child: Container(
        margin: const EdgeInsets.only(top: 10),
        padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 10),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(10.0),
          color: Colors.white,
        ),
        child: Column(
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Flexible(
                  child: Text(
                    "订单编号:$sn",
                    style: const TextStyle(fontSize: 13, fontWeight: FontWeight.w300),
                    overflow: TextOverflow.ellipsis, // 使文字内容溢出时显示省略号
                    maxLines: 2, // 最多显示2行
                  ),
                ),
                statusWidget,
              ],
            ),
            const SizedBox(height: 10),
            _buildGoodItemWidget(),
            const SizedBox(height: 10),
            priceWidget,
            const SizedBox(height: 10),
            operateWidget,
          ],
        ),
      ),
    );
  }

  Widget _buildGoodItemWidget() {
    return Column(
      children: [
        for (var item in goodsList) ...[
          Row(
            children: [
              ClipRRect(
                borderRadius: BorderRadius.circular(10.0),
                child: BaseImage(
                  url: item['img'],
                  width: 100.w,
                  height: 100.w,
                ),
              ),
              Container(
                margin: EdgeInsets.only(left: 10.w),
                child: Row(
                  children: [
                    Column(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Row(
                          children: [
                            Container(
                              color: Tools.fromHex("#FFEEEE"),
                              padding: EdgeInsets.fromLTRB(5.w, 2.w, 5.w, 2.w),
                              margin: EdgeInsets.only(right: 5.w),
                              child: goodsTypeTag(getGoodsTypeName(item['commodityType']), margin: const EdgeInsets.only(right: 5)),
                            ),
                          ],
                        ),
                        const SizedBox(height: 10),
                        SizedBox(
                          width: 160.w,
                          child: Text(
                            item['goodsName'],
                            softWrap: true,
                            maxLines: 2,
                            overflow: TextOverflow.ellipsis,
                            style: const TextStyle(fontSize: 14, fontWeight: FontWeight.w300),
                          ),
                        ),
                      ],
                    ),
                    Column(
                      children: [
                        Text(
                          "￥${item['price']}",
                          style: const TextStyle(fontSize: 15, fontWeight: FontWeight.w300),
                        ),
                        Text(
                          "共${item['buyNum']}件",
                          style: TextStyle(fontSize: 11, fontWeight: FontWeight.w500, color: Tools.fromHex("#999999")),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ],
          ),
          // 打印 item 的数据到控制台
          Builder(
            builder: (context) {
              print("Processing item: $item");
              return const SizedBox.shrink(); // 这个组件不会展示任何内容
            },
          ),
        ],
      ],
    );
  }

  Widget _buttons(
    String title,
    Callback onPressed, {
    String? color = "#cccccc",
    double? height = 28,
    double? fontSize = 13,
    EdgeInsets? margin,
  }) {
    return Container(
      margin: margin ?? margin,
      height: height,
      child: OutlinedButton(
          style: OutlinedButton.styleFrom(
            padding: EdgeInsets.fromLTRB(10.w, 3.w, 10.w, 3.w),
            side: BorderSide(color: Tools.fromHex(color!)), // 设置边界颜色
          ),
          onPressed: onPressed,
          child: Text(
            title,
            style: TextStyle(
              fontSize: fontSize,
              color: Tools.fromHex(color),
              fontWeight: FontWeight.w500,
            ),
          )),
    );
  }

  /// 状态样式
  Widget createStatusWidget() {
    late Widget payStatusStyleWidget;

    var statusCode = widget.itemInfo['status'];
    OrderStatus status = OrderStatus.fromValue(statusCode);
    switch (status) {
      case OrderStatus.pendingPayment:
        payStatusStyleWidget = SizedBox(
          child: Row(
            mainAxisAlignment: MainAxisAlignment.end,
            children: [
              Container(
                padding: EdgeInsets.fromLTRB(4.w, 2.w, 4.w, 2.w),
                decoration: BoxDecoration(color: Tools.fromHex("#F83F2D"), borderRadius: const BorderRadius.horizontal(left: Radius.circular(20.0))),
                child: const Text("等待付款", style: TextStyle(color: Colors.white, fontSize: 10, fontWeight: FontWeight.w300)),
              ),
              Container(
                padding: EdgeInsets.fromLTRB(4.w, 2.w, 4.w, 2.w),
                decoration: BoxDecoration(color: Tools.fromHex("#FFC7C7"), borderRadius: const BorderRadius.horizontal(right: Radius.circular(20.0))),
                child: CustomCountdownTimer(endTime: DateTime.parse(widget.itemInfo['pendingPaymentTime']), onEnd: () {}),
              ),

              //CustomCountdownTimer(endTime: DateTime.parse(widget.itemInfo['pendingPaymentTime']), onEnd: () {}),
            ],
          ),
        );
      case OrderStatus.pendingShipment:
        if (finalStatus == 0) {
          payStatusStyleWidget = Text(
            ' ${widget.itemInfo['presaleEndTime']} 前支付',
            style: TextStyle(color: Tools.fromHex('#F83F2D'), fontSize: 10, fontWeight: FontWeight.w300),
          );
        } else {
          payStatusStyleWidget = Align(
            alignment: Alignment.centerRight,
            child: Text(
              '待发货',
              style: TextStyle(color: Tools.fromHex('#F83F2D'), fontSize: 10, fontWeight: FontWeight.w300),
            ),
          );
        }

      case OrderStatus.shipped:
        payStatusStyleWidget = Text(
          '待收货',
          style: TextStyle(color: Tools.fromHex('#F83F2D'), fontSize: 10, fontWeight: FontWeight.w300),
        );
      case OrderStatus.canceled:
        payStatusStyleWidget = Text(
          '已取消',
          style: TextStyle(color: Tools.fromHex('#F83F2D'), fontSize: 10, fontWeight: FontWeight.w300),
        );
      case OrderStatus.completed:
        payStatusStyleWidget = Text(
          '已完成',
          style: TextStyle(color: Tools.fromHex('#F83F2D'), fontSize: 10, fontWeight: FontWeight.w300),
        );
      default:
        payStatusStyleWidget = const SizedBox();
    }

    return payStatusStyleWidget;
  }

  /// 价格样式
  Widget createPriceWidget() {
    late Widget priceStyleWidget;

    var statusCode = widget.itemInfo['status'];
    OrderStatus status = OrderStatus.fromValue(statusCode);
    switch (status) {
      case OrderStatus.pendingPayment:
        if (presaleType == 2) {
          priceStyleWidget = Row(
            mainAxisAlignment: MainAxisAlignment.end,
            mainAxisSize: MainAxisSize.max,
            children: [
              Text('实付款', style: TextStyle(color: Tools.fromHex('#333333'), fontSize: 12, fontWeight: FontWeight.w300)),
              const SizedBox(width: 5),
              Text('¥', style: TextStyle(color: Tools.fromHex('#F83F2D'), fontSize: 10, fontWeight: FontWeight.w500)),
              Text(widget.itemInfo['priceOrder'].toString(), style: TextStyle(color: Tools.fromHex('#F83F2D'), fontSize: 15, fontWeight: FontWeight.w300)),
            ],
          );
        } else if (presaleType == 1) {
          priceStyleWidget = Row(
            mainAxisAlignment: MainAxisAlignment.end,
            mainAxisSize: MainAxisSize.max,
            children: [
              Text('待支付尾款金额', style: TextStyle(color: Tools.fromHex('#333333'), fontSize: 12, fontWeight: FontWeight.w300)),
              const SizedBox(width: 5),
              Text('¥', style: TextStyle(color: Tools.fromHex('#F83F2D'), fontSize: 10, fontWeight: FontWeight.w500)),
              Text(widget.itemInfo['finalPay'].toString(), style: TextStyle(color: Tools.fromHex('#F83F2D'), fontSize: 15, fontWeight: FontWeight.w300)),
            ],
          );
        }

      case OrderStatus.pendingShipment:
        priceStyleWidget = Row(
          mainAxisAlignment: MainAxisAlignment.end,
          mainAxisSize: MainAxisSize.max,
          children: [
            Text('实付款', style: TextStyle(color: Tools.fromHex('#333333'), fontSize: 12, fontWeight: FontWeight.w300)),
            const SizedBox(width: 5),
            Text('¥', style: TextStyle(color: Tools.fromHex('#F83F2D'), fontSize: 10, fontWeight: FontWeight.w500)),
            Text(widget.itemInfo['priceOrder'].toString(), style: TextStyle(color: Tools.fromHex('#F83F2D'), fontSize: 15, fontWeight: FontWeight.w300)),
          ],
        );
      case OrderStatus.shipped:
        priceStyleWidget = Row(
          mainAxisAlignment: MainAxisAlignment.end,
          mainAxisSize: MainAxisSize.max,
          children: [
            Text('实付款', style: TextStyle(color: Tools.fromHex('#333333'), fontSize: 12, fontWeight: FontWeight.w300)),
            const SizedBox(width: 5),
            Text('¥', style: TextStyle(color: Tools.fromHex('#F83F2D'), fontSize: 10, fontWeight: FontWeight.w500)),
            Text(widget.itemInfo['priceOrder'].toString(), style: TextStyle(color: Tools.fromHex('#F83F2D'), fontSize: 15, fontWeight: FontWeight.w300)),
          ],
        );
      case OrderStatus.canceled:
        priceStyleWidget = Row(
          mainAxisAlignment: MainAxisAlignment.end,
          mainAxisSize: MainAxisSize.max,
          children: [
            Text('实付款', style: TextStyle(color: Tools.fromHex('#333333'), fontSize: 12, fontWeight: FontWeight.w300)),
            const SizedBox(width: 5),
            Text('¥', style: TextStyle(color: Tools.fromHex('#F83F2D'), fontSize: 10, fontWeight: FontWeight.w500)),
            Text(widget.itemInfo['priceOrder'].toString(), style: TextStyle(color: Tools.fromHex('#F83F2D'), fontSize: 15, fontWeight: FontWeight.w300)),
          ],
        );
      case OrderStatus.completed:
        priceStyleWidget = Row(
          mainAxisAlignment: MainAxisAlignment.end,
          mainAxisSize: MainAxisSize.max,
          children: [
            Text('实付款', style: TextStyle(color: Tools.fromHex('#333333'), fontSize: 12, fontWeight: FontWeight.w300)),
            const SizedBox(width: 5),
            Text('¥', style: TextStyle(color: Tools.fromHex('#F83F2D'), fontSize: 10, fontWeight: FontWeight.w500)),
            Text(widget.itemInfo['priceOrder'].toString(), style: TextStyle(color: Tools.fromHex('#F83F2D'), fontSize: 15, fontWeight: FontWeight.w300)),
          ],
        );
      default:
        priceStyleWidget = const SizedBox();
    }

    return priceStyleWidget;
  }

  /// 操作按钮样式
  Widget createOperateWidget() {
    late Widget bottomWidget;

    var statusCode = widget.itemInfo['status'];
    OrderStatus status = OrderStatus.fromValue(statusCode);

    switch (status) {
      case OrderStatus.pendingPayment:
        bottomWidget = Row(
          mainAxisAlignment: MainAxisAlignment.end,
          mainAxisSize: MainAxisSize.max,
          children: [
            if (presaleType == 2) ...[
              // 定金预售，支付定金，支付尾款，已经在待发货的状态了，这里不处理
              SizedBox(
                height: 30.h,
                child: _buttons("取消订单", color: "#333333", () {
                  if (widget.onCallback != null) {
                    widget.onCallback!(OperateActionType.cancelOrder, widget.itemInfo);
                  }
                }),
              ),
              const SizedBox(width: 5),
              SizedBox(
                height: 30.h,
                child: _buttons("支付定金", color: "#F83F2D", () {
                  if (widget.onCallback != null) {
                    widget.onCallback!(OperateActionType.depositPayment, widget.itemInfo);
                  }
                }),
              ),
            ] else if (presaleType == 1) ...[
              // 全款预售，待支付
              SizedBox(
                height: 30.h,
                child: _buttons("取消订单", color: "#333333", () {
                  if (widget.onCallback != null) {
                    widget.onCallback!(OperateActionType.cancelOrder, widget.itemInfo);
                  }
                }),
              ),
              const SizedBox(width: 5),
              SizedBox(
                height: 30.h,
                child: _buttons("继续支付", color: "#333333", () {
                  if (widget.onCallback != null) {
                    widget.onCallback!(OperateActionType.goOnPayment, widget.itemInfo);
                  }
                }),
              ),
            ],
          ],
        );

      case OrderStatus.pendingShipment:
        if (presaleType == 1) {
          // 全款预售
          bottomWidget = const SizedBox();
        } else {
          if (finalStatus == 0) {
            // 定金预售，支付尾款
            bottomWidget = Row(
              mainAxisAlignment: MainAxisAlignment.end,
              mainAxisSize: MainAxisSize.max,
              children: [
                SizedBox(
                  height: 30.h,
                  child: _buttons("申请售后", color: "#333333", () {
                    if (widget.onCallback != null) {
                      widget.onCallback!(OperateActionType.requestReturn, widget.itemInfo);
                    }
                  }),
                ),
                const SizedBox(width: 10),
                SizedBox(
                  height: 30.h,
                  child: _buttons("支付尾款", color: "#F83F2D", () {
                    if (widget.onCallback != null) {
                      widget.onCallback!(OperateActionType.finalPayment, widget.itemInfo);
                    }
                  }),
                ),
              ],
            );
          } else {
            bottomWidget = Row(
              mainAxisAlignment: MainAxisAlignment.end,
              mainAxisSize: MainAxisSize.max,
              children: [
                SizedBox(
                  height: 30.h,
                  child: _buttons("申请售后", color: "#333333", () {
                    if (widget.onCallback != null) {
                      widget.onCallback!(OperateActionType.requestReturn, widget.itemInfo);
                    }
                  }),
                )
              ],
            );
          }
        }
      case OrderStatus.shipped:
        bottomWidget = SizedBox(
          height: 30.h,
          child: _buttons("确认收货", color: "#F83F2D", () {
            if (widget.onCallback != null) {
              widget.onCallback!(OperateActionType.confirmOrder, widget.itemInfo);
            }
          }),
        );
      case OrderStatus.canceled:
        bottomWidget = const SizedBox();
      case OrderStatus.completed:
        bottomWidget = const SizedBox();
      default:
        bottomWidget = const SizedBox();
    }

    return bottomWidget;
  }
}

enum OperateActionType {
  goOnPayment, // 继续支付，全款预售
  depositPayment, // 定金支付
  finalPayment, // 尾款支付
  requestReturn, // 申请售后
  cancelOrder, // 取消订单
  confirmOrder, // 确认收货
}
